package dao

import (
	"log"
	"time"
	"ztool/common"
)

// Blacklist 黑名单
type Blacklist struct {
	ID          uint
	Token       string //token
	ExpiresDate int64
}

// AddBlackList 添加到黑名单
func AddBlackList(tokenStr string, expiresAt int64) {
	db := common.GetDB()

	if !GetBlackListFromDB(tokenStr) {
		db.Model(&Blacklist{}).Create(&Blacklist{Token: tokenStr, ExpiresDate: expiresAt})
	}
}

// GetBlackListFromDB 从黑名单加载
func GetBlackListFromDB(tokenStr string) bool {
	var rows int64
	db := common.GetDB()
	db.Model(&Blacklist{}).Where("token = ?", tokenStr).Count(&rows)

	return rows > 0
}

// RemoveAllExpires 删除所有过期的黑名单token
func RemoveAllExpires() {
	log.Printf("删除过期tokenn %d", time.Now().Unix())
	db := common.GetDB()
	db.Where("expires_date <= ?", time.Now().Unix()).Delete(&Blacklist{})
}
